import api from '@/api/index.js';
import {redirect} from "react-router-dom"
import {userActions} from '@/store/actions/userAction.js';
import  store from "@/store/index.js";
import {saveData} from "@/utils/localstorage.js";

export default async function loginAction({request}) {
    const dispatch = store.dispatch;
    const formData = await request.formData();
    //获取表单字段
    const email = formData.get("email");
    const password = formData.get("password");


//     数据校验
    const errors = {};
    if (typeof email !== "string" || !email.includes('@')) {
        errors.email = "邮箱格式不正确";
    }
    if (typeof password !== "string" || password.length < 6) {
        errors.password = "请输入字符长度大于6位的密码";
    }
    if (Object.keys(errors).length) return errors;
    const response = await api.user.login(email, password);
    if (response && response.status !== 1) {
        throw new Error(response.message);
    }
    // 同步到store
    const  currentUser = response.data;
    dispatch(userActions(currentUser))
    //同步到localstorage
    saveData("currentUser",currentUser)
    return redirect('/')
}